package com.mibao.core;

import android.content.*;
import android.content.pm.PackageManager;
import android.util.Log;
import com.mibao.activity.MainActivity;
import com.mibao.db.DBAdapter;

import java.io.*;

public class privacyTrunkReceiver extends BroadcastReceiver {

	private Context context;
	private String exe_path = "data/local/inject"; // 注入模块代码路径
	private File exe_file;         
	/**
	 * @author 谢印超:HOOK号码已经重新定义为广播模式，非root模式。
	 *         ROOT模式调用jni
	 */
	@Override
	public void onReceive(Context text, Intent intent) {

		//String PhoneNum = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
		DBAdapter pwdDAO = new DBAdapter(text).open();
		String password = pwdDAO.getPassword();

		if (password.equals(this.getResultData())) { // this.getResultData()
			this.context = text;
			SharedPreferences settings = context.getSharedPreferences("SETTING_INFO", 0);
			boolean IsAllowed = settings.getBoolean("IsAllowed", false);
			if (!IsAllowed) {
				setResultData(null);
				intent.setClass(context, MainActivity.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				ComponentName activityName = new ComponentName(context, MainActivity.class);
				PackageManager pm = context.getPackageManager();
				pm.setComponentEnabledSetting(activityName, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
				context.startActivity(intent);
			}
			settings.edit().putBoolean("IsAllowed", false).commit();
			this.clearAbortBroadcast();
		} else {}
	}

	// HOOK服务器模块调用
	public boolean injectHook() throws IOException {
		copyBigDataToSD(exe_path);
		exe_file = new File(exe_path);
		exe_file.setExecutable(true, true);
		execCmd(exe_path);
		return true;
	}

	private void execCmd(String cmd) throws IOException {

		Runtime runtime = Runtime.getRuntime();
		Process process = runtime.exec(cmd);
		InputStream is = process.getInputStream();
		InputStreamReader isr = new InputStreamReader(is);
		BufferedReader br = new BufferedReader(isr);
		String line = null;
		while (null != (line = br.readLine())) {
			Log.e("########", line);
		}
		try {
			process.waitFor();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

	}

	private void copyBigDataToSD(String strOutFileName) throws IOException {
		// TODO Auto-generated method stub
		InputStream myInput;
		OutputStream myOutput = new FileOutputStream(strOutFileName);
		// getAssets()方法必须要用context调用
		myInput = context.getAssets().open("inject");
		byte[] buffer = new byte[1024];
		int length = myInput.read(buffer);
		while (length > 0) {
			myOutput.write(buffer, 0, length);
			length = myInput.read(buffer);
		}
		myOutput.flush();
		myInput.close();
		myOutput.close();
	}

	public void Allowed() {

	}

}
